package com.sinoglobal.ningxia.activity.amusement;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.ab.view.listener.AbOnListViewListener;
import com.ab.view.pullview.AbPullListView;
import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.activity.IBase;
import com.sinoglobal.ningxia.activity.MyCollectionActivity;
import com.sinoglobal.ningxia.adapter.CommentAdapter;
import com.sinoglobal.ningxia.adapter.PhotoAdapter;
import com.sinoglobal.ningxia.beans.BusinessDetailVo;
import com.sinoglobal.ningxia.beans.CommentIdVo;
import com.sinoglobal.ningxia.beans.CommentInfoVo;
import com.sinoglobal.ningxia.beans.CommentListVo;
import com.sinoglobal.ningxia.beans.CommentSubmitVo;
import com.sinoglobal.ningxia.beans.RootVo;
import com.sinoglobal.ningxia.downdata.imp.RemoteImpl;
import com.sinoglobal.ningxia.frame.FlyApplication;
import com.sinoglobal.ningxia.frame.ShareAbstractActivity;
import com.sinoglobal.ningxia.http.Code;
import com.sinoglobal.ningxia.http.ConnectionUtil;
import com.sinoglobal.ningxia.upload.SelectPicActivity;
import com.sinoglobal.ningxia.utils.Bimp;
import com.sinoglobal.ningxia.utils.BitmapUtiles;
import com.sinoglobal.ningxia.utils.EquipmentUtil;
import com.sinoglobal.ningxia.utils.ItktLog;
import com.sinoglobal.ningxia.utils.MContants;
import com.sinoglobal.ningxia.utils.TextUtil;
import com.sinoglobal.ningxia.widget.FiveStarsSeekBar;
import com.sinoglobal.ningxia.widget.MyProgressDialog;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;

/**
 * 商家详情
 * 
 * @author hxp
 * @createdate 2014-6-23 下午5:13:07
 * @Description:
 */
public class BusinessDetailActivity extends ShareAbstractActivity implements IBase,
		OnClickListener, AbOnListViewListener {
	private TextView share, comment, phone;// 分享，评论
	private CheckBox collect;// 收藏
	// private XListView commentListView;// 评论列表
	private AbPullListView commentListView;// 评论列表
	private CommentAdapter commentAdapter;// 评论适配器
	private ArrayList<CommentInfoVo> commentList;// 评论列表
	private String shareContent;// 分享内容
	private ArrayList<String> uploadImgs;// 要上传的图片
	private PopupWindow mPopupWindow;// 评论框
	private String shopId;// 商店id
	private String shoptype;// 商店类型
	public final String LOGTAG = "--MultiUpLoad--";// 关于文件上传的log
	public static final int NONE = 0;
	public final static int PIC_NUM = 9;// 最大图片数
	protected static final int TO_UPLOAD_FILE = 1;// 去上传文件
	protected static final int UPLOAD_FILE_DONE = 2;// 上传文件响应
	public static final int TO_SELECT_PHOTO = 3;// 选择文件
	public static final int PHOTORESOULT = 4;// 结果
	public static final int SET_DEFAULT_PHOTO = 6;// 设为默认图
	public static final int SET_HIDE_PHOTO = 7;// 设为隐藏图
	public static final int SET_NORMAL_PHOTO = 8;// 设为普通图
	public static final String IMAGE_UNSPECIFIED = "image/*";// 选择文件类型
	private int addFalg = 1; // 1 替换 2添加;
	private int mPosition;
	private int imgInfoIndex = 0;// 上传图片的下标
	final int MSG_NEXT_IMG = 2;
	private static Handler handler;// 文件上传的handler
	private MyProgressDialog pd;// 文件上传进度条
	private PhotoAdapter pAdapter;// 图片上传的adapter
	private int pageNum;// 评论页数
	private String commentId;// 添加评论的id
	private boolean collected = false;
	private boolean firstIn = false;// 首次进入此页面加载时屏蔽掉toast；
	public static final String SHOPID = "shopId";
	public static final String SHOPNAME = "shopName";
	public static final String TYPEID = "typeId";
	private String isFromCollection = "";//是否是从收藏界面进入

	private String phonenum = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.business_detail);
		init();
		showListener();
		loadBusinessInfo();
		loadComment(pageNum);
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		for (String picPath : BitmapUtiles.picPathTemp) {
			if (uploadImgs.size() == PIC_NUM) { // 最多8张
				uploadImgs.set(uploadImgs.size() - 1, picPath);
			} else {
				uploadImgs.add(uploadImgs.size() - 1, picPath);
			}
		}
		BitmapUtiles.picPathTemp.clear();
	}

	@SuppressLint("HandlerLeak")
	@Override
	public void init() {
		isFromCollection = getIntent().getStringExtra(
				FlyApplication.isFromCollection);
		shopId = getIntent().getStringExtra(SHOPID);
		String shopName = getIntent().getStringExtra(SHOPNAME);
		shoptype = getIntent().getStringExtra(TYPEID);
		pageNum = 0;
		titleView.setText(shopName);
		commentList = new ArrayList<CommentInfoVo>();
		commentAdapter = new CommentAdapter(this, commentList);
		commentListView = (AbPullListView) findViewById(R.id.business_comments);
		commentListView.getHeaderView().setHeaderProgressBarDrawable(
				this.getResources().getDrawable(R.drawable.progress_circular));
		commentListView.getFooterView().setFooterProgressBarDrawable(
				this.getResources().getDrawable(R.drawable.progress_circular));
		commentListView.setAdapter(commentAdapter);
		commentListView.setPullRefreshEnable(false);
		commentListView.setPullLoadEnable(true);
		comment = (TextView) findViewById(R.id.setledown_phone_num);
		phone = (TextView) findViewById(R.id.setledown_phone_play);
		phone.setVisibility(View.VISIBLE);
		collect = (CheckBox) findViewById(R.id.setledown_collect);
		share = (TextView) findViewById(R.id.setledown_shard);
		Drawable drawable = getResources()
				.getDrawable(R.drawable.footer_record);
		drawable.setBounds(0, 0, drawable.getMinimumWidth(),
				drawable.getMinimumHeight());
		comment.setCompoundDrawables(drawable, null, null, null);
		comment.setText(getString(R.string.comment));

		pd = new MyProgressDialog(BusinessDetailActivity.this,
				getString(R.string.uploading_img));
		pd.setCancelable(false);
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 1:
					BusinessDetailActivity.this.finish();
					break;
				case MSG_NEXT_IMG:// 上传下一张图片
					pd.setProgress(imgInfoIndex);
					Log.i(LOGTAG, "imgInfoIndex==" + imgInfoIndex);
					if (imgInfoIndex < pd.getMax()) {
						uploadImgInfo();
					} else {
						pd.dismiss();
						showShortToastMessage(getString(R.string.uploaded_img));
						removePop();
					}
					break;
				default:
					break;
				}
			}
		};
	}

	private void loadBusinessInfo() {
		new ItktAsyncTaskWithDialog<Void, Void, BusinessDetailVo>(getString(R.string.loading_detail),
				false, false) {
			@Override
			public BusinessDetailVo before(Void... params) throws Exception {
				return RemoteImpl.getInstance().getBusinessDetailVo(shopId,
						shoptype);
			}

			@Override
			public void after(BusinessDetailVo result) {
				if (null == result) {
					return;
				}
				if (Code.CODE_SUCCESS == result.getCode()) {
					setData(result);
				} else {
					showShortToastMessage(result.getMessage());
				}
				return;
			}

			@Override
			public void exception() {
			}
		}.execute();
	}

	/**
	 * 
	 * @author wxy
	 * @createdate 2014-8-4 下午5:27:13
	 * @Description: 加载评论
	 * @param pageNum
	 * 
	 */
	private void loadComment(int pageNum) {
		new ItktAsyncTaskWithDialog<Integer, Void, CommentListVo>(getString(R.string.loading_comments),
				false, true) {

			@Override
			public CommentListVo before(Integer... params) throws Exception {
				return RemoteImpl.getInstance().getBusinessCommentList(shopId,
						params[0]);
			}

			@Override
			public void after(CommentListVo result) {
				if (null == result) {
					return;
				}
				if (Code.CODE_SUCCESS == result.getCode()) {
					setComment(result);
					return;
				} else {
					showShortToastMessage(result.getMessage());
				}
			}

			@Override
			public void exception() {
			}
		}.execute(pageNum);
	}

	/**
	 * 
	 * @author wxy
	 * @createdate 2014-7-23 下午4:56:51
	 * @Description: 点击收藏按钮
	 * 
	 */
	private void addCollection(final String type) {
		final String enterType="1";
		final String foodType="2";
		final String collectionType = getIntent().getExtras().getString(
				BusinessDetailActivity.TYPEID);
		new ItktAsyncTaskWithDialog<Void, Void, RootVo>(MContants.EMPTY_STRING, false, false) {
			@Override
			public RootVo before(Void... params) throws Exception {
				ItktLog.i("收藏执行了。。。。。" + FilterRequirement.TYPE + "和" + type
						+ "和" + shopId + "和" + collectionType);
				// 判断是娱乐的收藏还是美食的收藏 1娱乐 2美食
				if (MContants.EMPTY_STRING.equals(FilterRequirement.TYPE)) {
					ItktLog.i("FilterRequirement.type==null");
					if (collected) {
						ItktLog.i("FilterRequirement.type==null===isChecked");
						collected = false;
						return RemoteImpl.getInstance().add2DelCollect(
								FlyApplication.userId,
								Byte.parseByte(collectionType),
								Byte.parseByte(foodType), shopId);

					} else {
						collected = true;
						return RemoteImpl.getInstance().add2DelCollect(
								FlyApplication.userId,
								Byte.parseByte(collectionType),
								Byte.parseByte(enterType), shopId);
					}
				} else {

					return RemoteImpl.getInstance().add2DelCollect(
							FlyApplication.userId,
							Byte.parseByte(FilterRequirement.TYPE),
							Byte.parseByte(type), shopId);
				}
			}

			@Override
			public void after(RootVo result) {
				collect.setClickable(true);
				if (Code.CODE_SUCCESS == result.getCode()) {
					if (type.equals(enterType)) {
						showShortToastMessage(getString(R.string.collectSuccess));
					} else {
						showShortToastMessage(getString(R.string.collectCancel));
					}
				}
			}

			@Override
			public void exception() {
			}
		}.execute();

	}

	@Override
	public void showListener() {
		share.setOnClickListener(this);
		phone.setOnClickListener(this);
		comment.setOnClickListener(this);
		// commentListView.setXListViewListener(this);
		commentListView.setAbOnListViewListener(this);
		collect.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				if (firstIn) {
					if (isLoginIntentLoginActivity()) {
						if (arg1) {
							collect.setClickable(false);
							addCollection(String.valueOf(1));
						} else {
							collect.setClickable(false);
							addCollection(String.valueOf(2));
						}
					} else {
						collect.setChecked(false);
					}
				} else {
					firstIn = true;
				}
			}
		});
		templateButtonLeft.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 如果是从我的收藏界面进入的话那么，返回键重新进入我的收藏界面。
				if ("1".equals(isFromCollection)) {
					Intent intent = new Intent(BusinessDetailActivity.this,
							MyCollectionActivity.class);
					BusinessDetailActivity.this.startActivity(intent);
					BusinessDetailActivity.this.finish();
				} else {
					BusinessDetailActivity.this.finish();
				}
			}
		});
	}

	/**
	 * 移除评论框
	 * 
	 * @author hxp
	 * @createdate 2014-7-9 下午2:52:12
	 * @Description: (用一句话描述该方法做什么)
	 * 
	 */
	private void removePop() {
		if (mPopupWindow != null && mPopupWindow.isShowing()) {
			mPopupWindow.dismiss();
			BitmapUtiles.clearCahe();
			mPopupWindow = null;
		}
	}

	// 设置动态值变量
	private void setData(BusinessDetailVo result) {
		if(TextUtil.stringIsNotNull(result.getShare_content()))
		shareContent = result.getShare_content();
		else
			shareContent=getString(R.string.code_share_content);
		if ("1".equals(result.getIs_collection())) {
			collected = true;

			collect.setChecked(true);

		} else {
			collect.setChecked(false);
			collected = false;
		}
		firstIn = true;
		if (result.getImglist() != null && result.getImglist().size() == 5) {
			result.getImglist().add(5, "addIcon");
		}
		result.setShopId(shopId);
		commentAdapter.setBusinessDetail(result);
		phonenum = result.getShop_tel();
	}

	// 设置评论
	private void setComment(CommentListVo result) {
		// 当评论为null的时候，如何显示点评item
		if (null != result.getList() && !result.getList().isEmpty()) {
			if (pageNum == 0) {
				commentList = result.getList();
			} else {
				commentList.addAll(result.getList());
			}
			commentAdapter.addData(commentList);
			commentAdapter.notifyDataSetChanged();
		} else {
			if (pageNum == 0) {
				// 给一个空的值，让第一个item显示出来。
				CommentInfoVo commentInfoVo = new CommentInfoVo();
				commentInfoVo.setId(MContants.EMPTY_STRING);
				commentInfoVo.setContent(MContants.EMPTY_STRING);
				commentInfoVo.setCreate_time(MContants.EMPTY_STRING);
				commentInfoVo.setNickname(MContants.EMPTY_STRING);
				commentInfoVo.setUser_id(MContants.EMPTY_STRING);
				commentInfoVo.setComment_star("0");
				commentList.add(commentInfoVo);
				commentAdapter.notifyDataSetChanged();
			}
			commentListView.setPullLoadEnable(false);
		}
		commentListView.stopLoadMore();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.setledown_shard:
			showPopwindow(true, shareContent, MContants.EMPTY_STRING, ConnectionUtil.MicDoorAdress);
			break;

		case R.id.setledown_phone_num:
			if (!isLoginIntentLoginActivity()) {
				return;
			}
			if (null == mPopupWindow) {
				View commentPop = getPopWindow();
				mPopupWindow = new PopupWindow(commentPop,
						LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
				mPopupWindow.setFocusable(true);
				mPopupWindow.setOutsideTouchable(true);
				mPopupWindow
						.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
				mPopupWindow
						.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
				mPopupWindow.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.content_bg));
			}
			int heightPx = EquipmentUtil.dip2px(this, 40);
			mPopupWindow.showAtLocation(findViewById(R.id.business_comments),
					Gravity.BOTTOM, 0, heightPx);
			break;
		case R.id.setledown_phone_play:
			if (TextUtil.stringIsNotNull(phonenum)) {
				Intent call_intent = new Intent(Intent.ACTION_DIAL,
						Uri.parse("tel:" + phonenum));
				call_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				if (call_intent != null) {
					startActivity(call_intent);
				}
			} else {
				showShortToastMessage(getString(R.string.no_phones));
			}
			break;
		default:
			break;
		}

	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		removePop();
		return super.onTouchEvent(event);
	}

	// 初始化评论PopWindow
	private View getPopWindow() {
		LayoutInflater mLayoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
		View pop = mLayoutInflater.inflate(R.layout.business_comment, null);
		final FiveStarsSeekBar commentStar = new FiveStarsSeekBar(this,
				EquipmentUtil.dip2px(this, 90), EquipmentUtil.dip2px(this, 18));
		commentStar.setSelectNums(0);
		LinearLayout starLayout = (LinearLayout) pop
				.findViewById(R.id.comment_star);
		starLayout.addView(commentStar);
		uploadImgs = new ArrayList<String>();
		uploadImgs.add("addIcon");
		pAdapter = new PhotoAdapter(this, uploadImgs, PhotoAdapter.TAG_UPLOAD);
		final EditText content = (EditText) pop
				.findViewById(R.id.edit_business);
		final TextView numLimit = (TextView) pop.findViewById(R.id.text_limit);
		final ImageView submit = (ImageView) pop
				.findViewById(R.id.comment_submit);

		content.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				int num = content.getText().length();
				if (num <= 50) {
					numLimit.setText(num + "/50");
					numLimit.setTextColor(Color.rgb(102, 102, 102));
					submit.setClickable(true);
				} else {
					numLimit.setText("-" + (num - 50) + "/50");
					numLimit.setTextColor(Color.rgb(255, 99, 92));
					submit.setClickable(true);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});

		// 提交评论
		submit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				// 如果用户没有选择星星，则提示用户
				if (!MContants.EMPTY_STRING.equals(content.getText().toString().trim())
						&& commentStar.getSelectNums() != 0) {
					if (content.getText().length() > 50) {
						String info = getString(R.string.commentInfo);
						info = MessageFormat.format(info, content.length());
						showShortToastMessage(info);
						return;
					}
					CommentSubmitVo params = new CommentSubmitVo();
					params.setContent(String.valueOf(content.getText()));
					params.setStar(commentStar.getSelectNums());
					params.setId(shopId);
					params.setType("3");
					new ItktAsyncTaskWithDialog<CommentSubmitVo, Void, CommentIdVo>(
							getString(R.string.submiting), false, true) {

						@Override
						public CommentIdVo before(CommentSubmitVo... params)
								throws Exception {
							return RemoteImpl.getInstance().submitComment(
									params[0], BusinessDetailActivity.this);
						}

						@Override
						public void after(CommentIdVo result) {
							if (null == result) {
								return;
							}
							if (Code.CODE_SUCCESS == result.getCode()) {
								// 多张图片上传入口
								// commentId = result.getId();
								// if(commentId != null && uploadImgs.size() >
								// 1){
								// pd.setMax(uploadImgs.size()-1);
								// pd.show();
								// handler.sendEmptyMessage(MSG_NEXT_IMG);
								// }else{
								removePop();
								// 重新加载评论列表
								pageNum = 0;
								loadComment(pageNum);
								// }
								showShortToastMessage(getString(R.string.comment_success));
							} else {
								showShortToastMessage(result.getMessage());
							}
						}

						@Override
						public void exception() {
						}

					}.execute(params);
				} else if (MContants.EMPTY_STRING.equals(content.getText().toString().trim())) {
					showShortToastMessage(getString(R.string.please_input_content));

				} else {
					showShortToastMessage(getString(R.string.please_choice_starts));
				}
			}
		});
		return pop;
	}

	@Override
	public void onBackPressed() {
		BitmapUtiles.clearCahe();
		if ("1".equals(isFromCollection)) {
			Intent intent = new Intent(BusinessDetailActivity.this,
					MyCollectionActivity.class);
			BusinessDetailActivity.this.startActivity(intent);
			BusinessDetailActivity.this.finish();
		} else {
			BusinessDetailActivity.this.finish();
		}
		super.onBackPressed();
	}

	// 图片上传
	private void uploadImgInfo() {
		new ItktAsyncTaskWithDialog<Void, Void, RootVo>(MContants.EMPTY_STRING, false, true) {

			private String image;

			@Override
			public RootVo before(Void... params) throws Exception {
				ItktLog.i(uploadImgs.get(0) + "--------------"
						+ uploadImgs.get(1) + "-----------" + uploadImgs.size());
				image = Bimp.uploadImgForBase64(Bimp
						.revitionImageSize(uploadImgs.get(imgInfoIndex)));
				return RemoteImpl.getInstance().updatePic(shoptype, commentId,
						image, "jpg");
			}

			@Override
			public void after(RootVo result) {
				if (null == result) {
					return;
				}
				if (Code.CODE_SUCCESS != result.getCode()) {
					String info = getString(R.string.upload_failed_img);
					info = MessageFormat.format(info, (imgInfoIndex + 1));
					showShortToastMessage(info);
				}
				imgInfoIndex++;
				handler.sendEmptyMessage(MSG_NEXT_IMG);
			}

			@Override
			public void exception() {

			}
		}.execute();

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK && requestCode == TO_SELECT_PHOTO) {
			// 正常选择图片
			String picPath = data
					.getStringExtra(SelectPicActivity.KEY_PHOTO_PATH);
			if (addFalg == 1) { // 替换
				uploadImgs.set(mPosition, picPath);
			} else { // 添加

				if (uploadImgs.size() == PIC_NUM) { // 最多9张数
					uploadImgs.set(uploadImgs.size() - 1, picPath);
				} else {
					uploadImgs.add(uploadImgs.size() - 1, picPath);
				}
			}
			if (pAdapter.getCount() > PIC_NUM) {
				// 添加新图片
			} else {

			}
		} else if (resultCode == Activity.RESULT_FIRST_USER
				&& requestCode == TO_SELECT_PHOTO) {
			// 删除
			uploadImgs.remove(mPosition);
			BitmapUtiles.drr.remove(mPosition);
			if (!uploadImgs.get(pAdapter.getCount() - 1).equals("addIcon")) {
				uploadImgs.add("addIcon");
			}
		}
		if (pAdapter != null && uploadImgs != null) {
			pAdapter.setData(uploadImgs);
			pAdapter.notifyDataSetChanged();
			Log.i(LOGTAG, "uploadImgs.size==" + uploadImgs.size());
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	
	//  获得指定文件的byte数组
	 
	public byte[] getBytes(File file) {
		byte[] buffer = null;
		try {
			FileInputStream fis = new FileInputStream(file);
			ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
			byte[] b = new byte[1000];
			int n;
			while ((n = fis.read(b)) != -1) {
				bos.write(b, 0, n);
			}
			fis.close();
			bos.close();
			buffer = bos.toByteArray();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return buffer;
	}

	public void setmPosition(int mPosition) {
		this.mPosition = mPosition;
	}

	public int getmPosition() {
		return mPosition;
	}

	public void setAddFalg(int addFalg) {
		this.addFalg = addFalg;
	}

	@Override
	public void onRefresh() {
		pageNum = 0;
		loadComment(pageNum);
	}

	@Override
	public void onLoadMore() {
		loadComment(++pageNum);
	}

}
